from flask import Blueprint, jsonify, request, json
import pymysql as sql
from Login.loginView import adminNum

admin = Blueprint('admin', __name__)

# 全局变量adminNum
# UserName是账户名，用户名是用户真实姓名

connect = sql.Connect(
    host='bj-cdb-hjbj4oh0.sql.tencentcdb.com',
    port=60670,
    user='root',
    passwd='Yuan2000_',
    db='tencentmysql',
    charset='utf8'
)
cursor = connect.cursor()


@admin.route('/userlist', methods=['POST', 'GET'])
def userlist():
    sql2 = "SELECT ID, UserName FROM sys_user"
    cursor.execute(sql2)
    rows = cursor.fetchall()
    object_list = []
    for row in rows:
        result = {"ID": row[0], "UserName": row[1]}
        object_list.append(result)
    res = json.dumps(object_list)
    return res


# 查看详细信息
@admin.route('/show_info', methods=['POST', 'GET'])
def show_info():
    sql3 = "SELECT * FROM sys_user where ID='" + adminNum + "'"
    print(sql3)
    cursor.execute(sql3)
    rows = cursor.fetchall()
    object_list = []
    for row in rows:
        result = {"ID": row[0], "UserName": row[3]}
        object_list.append(result)
    res = json.dumps(object_list)
    return result


# 修改详细信息
@admin.route('/update_info_admin', methods=['POST', 'GET'])
def update_info():
    data = request.get_data()
    json_data = json.loads(data.decode("utf-8"))
    name = json_data.get('UserName')
    name2 = json_data.get('REAL_NAME')
    email = json_data.get('EMAIL')
    themes = json_data.get('theme')
    sql4 = "UPDATE sys_user SET UserName = '" + str(name) + "', REAL_NAME = '" + str(name2) + "', EMAIL= '" + str(email) + \
           "', theme = '" + str(themes) + "' WHERE ID = '" + str(62) + "'"
    print(sql4)

    try:
        cursor.execute(sql4)
        connect.commit()
    except:
        return jsonify(0)
    else:
        return jsonify(1)
